<template>
  <div class="patient-detail">
    <van-nav-bar
      title="患者详情"
      left-arrow
      @click-left="router.back()"
      fixed
    />

    <!-- 基本信息 -->
    <div class="info-card">
      <van-cell-group inset>
        <van-cell center>
          <template #icon>
            <van-image
              round
              width="60"
              height="60"
              :src="patientInfo.avatar || defaultAvatar"
              style="margin-right: 12px"
            />
          </template>
          <template #title>
            <div class="patient-info">
              <span class="name">{{ patientInfo.realName }}</span>
              <van-tag type="primary">{{ patientInfo.gender === 1 ? '男' : '女' }}</van-tag>
            </div>
          </template>
          <template #label>
            <div class="details">
              <span>年龄：{{ patientInfo.age || '未知' }}</span>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 病史信息 -->
    <div class="medical-info">
      <van-cell-group inset>
        <van-cell title="病史信息">
          <template #right-icon>
            <van-button size="small" type="primary" @click="showEditDialog">
              编辑
            </van-button>
          </template>
        </van-cell>
        <van-cell title="既往病史" :value="patientInfo.medicalHistory || '无'" />
        <van-cell title="家族病史" :value="patientInfo.familyHistory || '无'" />
        <van-cell title="过敏史" :value="patientInfo.allergies || '无'" />
        <van-cell title="居住地址" :value="patientInfo.address || '未填写'" />
      </van-cell-group>
    </div>

    <!-- 健康记录 -->
    <div class="records-card">
      <van-cell-group inset>
        <van-cell title="健康记录" />
        <template v-if="healthRecords.length">
          <div class="record-list">
            <div v-for="(group, date) in groupedRecords" :key="date" class="record-group">
              <div class="record-date">{{ formatDate(date) }}</div>
              <div class="record-items">
                <div v-for="record in group" :key="record.id" class="record-item">
                  <span class="record-type">{{ getRecordTypeName(record.recordType) }}</span>
                  <span class="record-value">{{ record.recordValue }}{{ getRecordUnit(record.recordType) }}</span>
                  <span class="record-time">{{ formatTime(record.createTime) }}</span>
                </div>
              </div>
            </div>
          </div>
        </template>
        <van-empty v-else description="暂无健康记录" />
      </van-cell-group>
    </div>

    <!-- 编辑弹窗 -->
    <van-dialog
      v-model:show="showDialog"
      title="编辑病史信息"
      show-cancel-button
      @confirm="handleSave"
    >
      <div class="edit-form">
        <van-field
          v-model="editForm.medicalHistory"
          label="既往病史"
          type="textarea"
          rows="2"
          placeholder="请输入既往病史"
        />
        <van-field
          v-model="editForm.familyHistory"
          label="家族病史"
          type="textarea"
          rows="2"
          placeholder="请输入家族病史"
        />
        <van-field
          v-model="editForm.allergies"
          label="过敏史"
          type="textarea"
          rows="2"
          placeholder="请输入过敏史"
        />
        <van-field
          v-model="editForm.address"
          label="居住地址"
          type="textarea"
          rows="2"
          placeholder="请输入居住地址"
        />
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getPatientDetail, getPatientHealthRecords, updatePatientInfo } from '@/api/doctor'
import defaultAvatar from '@/assets/default-avatar.png'

const route = useRoute()
const router = useRouter()
const patientId = route.params.id

const patientInfo = ref({})
const healthRecords = ref([])
const showDialog = ref(false)
const editForm = ref({
  medicalHistory: '',
  familyHistory: '',
  allergies: '',
  address: ''
})

// 按日期分组的健康记录
const groupedRecords = computed(() => {
  const groups = {}
  healthRecords.value.forEach(record => {
    const date = record.createTime.split(' ')[0]
    if (!groups[date]) {
      groups[date] = []
    }
    groups[date].push(record)
  })
  return groups
})

// 获取记录类型名称
const getRecordTypeName = (type) => {
  const types = {
    1: '血压',
    2: '血糖',
    3: '体重',
    4: '体温'
  }
  return types[type] || '未知'
}

// 获取记录单位
const getRecordUnit = (type) => {
  const units = {
    1: 'mmHg',
    2: 'mmol/L',
    3: 'kg',
    4: '°C'
  }
  return units[type] || ''
}

// 显示编辑弹窗
const showEditDialog = () => {
  editForm.value = {
    medicalHistory: patientInfo.value.medicalHistory || '',
    familyHistory: patientInfo.value.familyHistory || '',
    allergies: patientInfo.value.allergies || '',
    address: patientInfo.value.address || ''
  }
  showDialog.value = true
}

// 保存编辑
const handleSave = async () => {
  try {
    const res = await updatePatientInfo(patientId, editForm.value)
    if (res.code === 200) {
      showToast('保存成功')
      Object.assign(patientInfo.value, editForm.value)
    } else {
      showToast(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    showToast('保存失败')
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleDateString()
}

// 格式化时间
const formatTime = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleTimeString()
}

// 加载患者详情
const loadPatientDetail = async () => {
  try {
    const res = await getPatientDetail(patientId)
    if (res.code === 200) {
      patientInfo.value = res.data
    }
  } catch (error) {
    console.error('获取患者详情失败:', error)
    showToast('获取患者详情失败')
  }
}

// 加载健康记录
const loadHealthRecords = async () => {
  try {
    const res = await getPatientHealthRecords(patientId)
    if (res.code === 200) {
      healthRecords.value = res.data
    }
  } catch (error) {
    console.error('获取健康记录失败:', error)
    showToast('获取健康记录失败')
  }
}

onMounted(() => {
  loadPatientDetail()
  loadHealthRecords()
})
</script>

<style lang="scss" scoped>
.patient-detail {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding: 46px 0 20px;

  .info-card,
  .medical-info,
  .records-card {
    margin: 12px 0;
  }

  .patient-info {
    display: flex;
    align-items: center;
    gap: 8px;

    .name {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .record-list {
    padding: 8px 16px;

    .record-group {
      margin-bottom: 16px;

      .record-date {
        font-size: 14px;
        color: #999;
        margin-bottom: 8px;
      }

      .record-items {
        .record-item {
          display: flex;
          align-items: center;
          padding: 8px 0;
          border-bottom: 1px solid #eee;

          .record-type {
            width: 60px;
            color: #666;
          }

          .record-value {
            flex: 1;
            color: #333;
            font-weight: 500;
          }

          .record-time {
            color: #999;
            font-size: 12px;
          }
        }
      }
    }
  }

  .edit-form {
    padding: 16px;
  }
}
</style>
